import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { Card, Form, Input, Checkbox, Button, message } from 'antd';
import { getUserToken } from '@/store';
import logo from '@/assets/images/logo.png';
import './index.scss';

const Login = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  const [loading, setLoading] = useState(false);

  // 表单校验规则
  const rules = {
    mobile: [
      // 多条校验逻辑，先校验第一条，如果第一条检验不通过，后面的就不会及进行校验 - 串行校验
      { required: true, message: '请输入手机号' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号' }
    ],
    code: [{ required: true, message: '请输入验证码' }],
    agree: [{ required: true, message: '请同意用户协议' }]
  };

  // 收集表单数据 - 表单的所有字段校验成功之后就会触发 onFinish 函数
  const onFinish = async ({ mobile, code }) => {
    setLoading(true);
    await dispatch(getUserToken({ mobile, code }));
    // 跳转首页
    navigate('/');
    // 提示用户是否登录成功
    message.success('登录成功');
  };

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        <Form
          validateTrigger="onBlur"
          onFinish={onFinish}
          initialValues={{ mobile: '13911111111', code: '246810', agree: true }}>
          <Form.Item name="mobile" rules={rules.mobile}>
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          <Form.Item name="code" rules={rules.code}>
            <Input size="large" placeholder="请输入验证码" />
          </Form.Item>
          <Form.Item name="agree" rules={rules.agree} valuePropName="checked">
            <Checkbox className="login-checkbox-label">我已阅读并同意「用户协议」和「隐私条款」</Checkbox>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block loading={loading}>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
